package com.lovelyj.trip_by_train.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lovelyj.trip_by_train.common.R;
import com.lovelyj.trip_by_train.entity.Administrator;
import com.lovelyj.trip_by_train.entity.Station;
import com.lovelyj.trip_by_train.service.StationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/station")
public class StationController {

    @Autowired
    private StationService stationService;

    @PutMapping("/create")
    public R<String> create(HttpServletRequest request, @RequestBody Station station) {
        log.info("开始创建");
        LambdaQueryWrapper<Station> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(station.getNameInChinese() != null, Station::getNameInChinese, station.getNameInChinese());
        if(stationService.count(lambdaQueryWrapper) > 0) {
            return R.error("该车站已创建");
        }
        stationService.save(station);
        return R.success("创建成功");
    }

    @GetMapping("/page")
    public R<Page<Station>> selectPage(HttpServletRequest request, Integer page, String nameInChinese, String nameInEnglish){
        log.info("selectPage..."+page);
        Page<Station> pageInfo=new Page<>(page,10);
        LambdaQueryWrapper<Station> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(nameInChinese!=null,Station::getNameInChinese,nameInChinese);
        queryWrapper.like(nameInEnglish!=null,Station::getNameInEnglish,nameInEnglish);
        stationService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

    @GetMapping("/selectAll")
    public R<List<Station>> selectMap(HttpServletRequest request){
        log.info("selectStations...");
        LambdaQueryWrapper<Station> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Station::getNameInEnglish);
        return R.success(stationService.list());
    }

    @PostMapping("/deleteByIds")
    public R<String> deleteByIds(HttpServletRequest request,@RequestBody List<Long> selectedIds){

        log.info("deleteByIds...");
        stationService.removeByIds(selectedIds);

        return R.success("删除成功");
    }

    @DeleteMapping
    public R<String> deleteById(HttpServletRequest request,Long id){

        log.info("deleteById..."+id);
        stationService.removeById(id);
        return R.success("删除成功");
    }


    @PutMapping("/update")
    public R<String> update(HttpServletRequest request,@RequestBody Station station) {
        log.info("update...");
        stationService.updateById(station);
        return R.success("修改成功");
    }
}
